<template>
  <div class="app-container">
    <el-card>
      <el-row :gutter="20" align="middle">
        <el-col :span="24" class="input-button-group">
          <el-button icon="el-icon-plus" type="primary" @click="openDialog">新增</el-button>
          <el-input v-model="username" placeholder="输入账号名称" clearable style="width: 200px;" />
          <el-select v-model="statusId" placeholder="选择账号状态" clearable>
            <el-option :value="11" label="启用" />
            <el-option :value="12" label="禁用" />
          </el-select>
          <el-button icon="el-icon-search" @click="handleSearch">筛选</el-button>
        </el-col>
      </el-row>
    </el-card>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      stripe
      height="532"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="ID" width="100" sortable :sort-by="sortById">
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>

      <el-table-column label="用户名" width="225" align="center">
        <template slot-scope="scope">
          <template v-if="isEditing(scope.row.id)">
            <el-input v-model="scope.row.username" size="small" />
          </template>
          <template v-else>
            {{ scope.row.username }}
          </template>
        </template></el-table-column>

      <el-table-column label="手机号" width="225" align="center">
        <template slot-scope="scope">
          <template v-if="isEditing(scope.row.id)">
            <el-input v-model="scope.row.phone" size="small" />
          </template>
          <template v-else>
            {{ scope.row.phone }}
          </template>
        </template></el-table-column>

      <el-table-column label="账号权限" width="225" align="center">
        <template slot-scope="scope">
          <template v-if="isEditing(scope.row.id)">
            <el-input v-model="scope.row.roles" size="small" />
          </template>
          <template v-else>
            {{ scope.row.roles }}
          </template>
        </template></el-table-column>

      <el-table-column label="账号状态" width="225" align="center">
        <template slot-scope="scope">
          <template v-if="isEditing(scope.row.id)">
            <el-select v-model="scope.row.statusId" size="small">
              <el-option :value="11" label="启用" />
              <el-option :value="12" label="禁用" />
            </el-select>
          </template>
          <template v-else>
            <span v-if="scope.row.statusId === 11" style="color: #4CAF50;">启用</span>
            <span v-if="scope.row.statusId === 12" style="color: #ff4949;">禁用</span>
          </template>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="277" align="center">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="toggleEdit(scope.row.id)"
          >{{ isEditing(scope.row.id) ? '保存' : '编辑' }}
          </el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row.id, scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="block" style="text-align: center;">
      <el-pagination
        :current-page="page"
        :page-sizes="[10, 10, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog
      title="新增用户"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="用户名">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input
            v-model="form.password"
            :type="showPassword ? 'text' : 'password'"
            placeholder="请输入密码"
            :suffix-icon="showPassword ? 'el-icon-view' : 'el-icon-hide'"
            @suffix-click.native="togglePasswordVisibility"
          />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleClose">取 消</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { getList, register, updateRow, deleteRow } from '@/api/user'

export default {
  name: 'User',
  data() {
    return {
      list: null,
      listLoading: true,
      page: 1,
      pageSize: 10,
      statusId: '',
      username: '',
      total: 0,
      dialogVisible: false,
      editingRowId: null,
      form: {
        username: '',
        password: '',
        phone: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    openDialog() {
      this.dialogVisible = true
      this.form.password = '123456'
    },
    handleClose() {
      this.form = {
        username: '',
        password: '',
        phone: ''
      }
      this.dialogVisible = false
    },
    handleSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          register(this.form).then(response => {
            this.$message.success('新增成功')
            this.handleClose()
            this.fetchData()
          })
        } else {
          console.log('表单验证失败')
          return false
        }
      })
    },
    fetchData() {
      this.listLoading = true
      getList({ page: this.page, pageSize: this.pageSize, statusId: this.statusId, username: this.username }).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      })
    },
    sortById(a, b) {
      return a.id - b.id
    },
    handleSearch() {
      this.page = 1
      this.fetchData()
    },
    handleSizeChange(size) {
      this.pageSize = size
      this.fetchData()
    },
    handleCurrentChange(page) {
      this.page = page
      this.fetchData()
    },
    handleDelete(rowId) {
      const ids = [rowId]
      this.$confirm('确定删除该记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteRow(ids).then(() => {
          this.fetchData()
          this.$message.success('删除成功')
        })
      }).catch(() => {
        this.$message('已取消删除')
      })
    },
    toggleEdit(rowId) {
      if (this.editingRowId === rowId) {
        this.saveChanges(rowId)
        this.editingRowId = null
      } else {
        this.editingRowId = rowId
      }
    },
    isEditing(rowId) {
      return this.editingRowId === rowId
    },
    saveChanges(rowId) {
      const updatedRow = this.list.find(row => row.id === rowId)
      updateRow(updatedRow).then(() => {
        this.$message.success('修改成功')
        this.fetchData()
      })
    }
  }
}
</script>

<style scoped>
.input-button-group {
  display: flex;
  align-items: center;
}

.input-button-group .el-input {
  flex: 1;
  margin-right: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>
